<template>
  <el-dialog
    title="用户注册"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible.sync="registerFormVisible"
    width="400px"
    @close="handleCloseRegisterForm"
  >
    <el-form
      ref="registerForm"
      :model="registerForm"
      :rules="registerRules"
      label-width="0px"
    >
      <!-- 用户名 -->
      <el-form-item prop="username">
        <el-input
          v-model="registerForm.username"
          placeholder="请输入账号（字母/数字）"
          maxlength="20"
        />
      </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          show-password
          placeholder="请输入密码（不少于6位）"
          maxlength="20"
        />
      </el-form-item>

      <!-- 确认密码（新增） -->
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          show-password
          placeholder="请再次输入密码"
          maxlength="20"
        />
      </el-form-item>

      <!-- 验证码（与登录一致） -->
      <el-row :gutter="10">
        <el-col :span="16">
          <el-form-item prop="code">
            <el-input v-model="registerForm.code" placeholder="请输入验证码" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <img class="captcha-img" :src="codeUrl" @click="getCode" />
        </el-col>
      </el-row>

      <!-- 注册按钮 + 去登录链接 -->
      <el-form-item>
        <el-button
          type="primary"
          :loading="loading"
          style="width:100%;"
          @click="handleRegister"
        >
          {{ loading ? '注册中...' : '注 册' }}
        </el-button>
        <div style=" margin-top: 10px;text-align: center;">
          <el-link type="info" @click="goLogin">已有账号？去登录</el-link>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
// 引入验证码接口和注册接口（需确保API路径正确）
import { getCodeImg } from '@/api/login'
import { mapState } from 'vuex'

export default {
  name: 'Register',
  data() {
    // 自定义验证：确认密码与密码一致
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      codeUrl: '', // 验证码图片地址
      loading: false, // 注册按钮加载状态
      // 注册表单数据
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        code: '', // 验证码输入值
        uuid: '', // 验证码唯一标识（对接后端）
      },
      // 注册表单验证规则
      registerRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '用户名长度必须介于 3-20 之间',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '密码长度必须介于 6-20 之间',
            trigger: 'blur',
          },
        ],
        confirmPassword: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' },
        ],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
      },
    }
  },
  computed: {
    registerFormVisible() {
      return this.$store.state.user.registerFormVisible
    },
  },
  watch: {
    registerFormVisible(val) {
      if (val) {
        this.getCode() // 弹窗显示时获取验证码
      }
    },
  },
  created() {
    // 初始化时获取验证码
    // this.getCode();
  },
  methods: {
    // 1. 获取验证码（与登录逻辑一致）
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = 'data:image/gif;base64,' + res.img // 渲染base64验证码
        this.registerForm.uuid = res.uuid // 保存验证码唯一标识
      })
    },

    // 2. 提交注册
    handleRegister() {
      // 表单验证
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 调用Vuex的Register action提交注册
          this.$store
            .dispatch('Register', this.registerForm)
            .then(() => {
              this.loading = false
              this.$message.success('注册成功！请登录')
              this.handleCloseRegisterForm() // 关闭注册弹窗
              this.$store.dispatch('showLoginForm') // 自动打开登录弹窗
            })
            .catch(() => {
              this.loading = false
              this.getCode() // 注册失败时刷新验证码
              this.$message.error('注册失败，请检查信息后重试')
            })
        }
      })
    },

    // 3. 跳转登录（关闭注册弹窗，打开登录弹窗）
    goLogin() {
      this.$store.commit('SET_REGISTERFORMVISIBLE', false)
      this.$store.dispatch('showLoginForm')
    },

    // 4. 关闭注册弹窗（重置表单）
    handleCloseRegisterForm() {
      this.$store.commit('SET_REGISTERFORMVISIBLE', false)
      // 重置表单（清除输入和验证状态）
      if (this.$refs.registerForm) {
        this.$refs.registerForm.resetFields()
      }
    },
  },
}
</script>

<style scoped>
/* 验证码图片样式（与登录一致） */
.captcha-img {
  display: block;
  width: 100%;
  height: 40px;
  border-radius: 4px;
  cursor: pointer;
}
</style>
